package com.education.api.open;

import com.education.business.service.system.SysEmailServiceImpl;
import com.education.common.exception.BusinessException;
import com.education.common.utils.Result;
import com.education.common.utils.ResultCode;
import com.education.model.dto.*;
import com.education.model.entity.SystemEmailLog;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/open/email")
@RequiredArgsConstructor
public class TestEmailController {

    private final SysEmailServiceImpl emailService;

    @PostMapping("/send")
    public Result<String> sendEmail(@RequestBody EmailRequest request) {
        try {
            EmailMessage message = convertToEmailMessage(request);
            emailService.sendAndLogEmail(message);
            return Result.success("邮件发送成功");
        } catch (SysEmailServiceImpl.EmailSendException e) {
            return Result.fail(ResultCode.FAIL,"邮件发送失败: " + e.getMessage());
        } catch (IOException e) {
            throw new BusinessException(e);
        }
    }

    @PostMapping(value = "/send_attachments",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result<String> sendEmail(
            @RequestPart @Valid EmailRequest request,
            @RequestPart(required = false) List<MultipartFile> attachments) {
        try {
            EmailMessage message = convertToEmailMessage(request, attachments);
            emailService.sendAndLogEmail(message);
            return Result.success("邮件发送成功");
        } catch (Exception e) {
            log.error("邮件发送异常", e);
            return Result.fail(ResultCode.FAIL,"邮件发送失败: " + e.getMessage());
        }
    }

    @GetMapping("/logs")
    public Result<Page<SystemEmailLog>> getEmailLogs(
            @RequestParam(required = false) String recipient,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        EmailLogQuery query = new EmailLogQuery();
        query.setRecipient(recipient);
        query.setStatus(status);
        query.setStartTime(startTime);
        query.setEndTime(endTime);

        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        return Result.success(emailService.getEmailLogs(query, pageable));
    }

    @GetMapping("/logs/{id}")
    public Result<SystemEmailLog> getEmailLogDetail(@PathVariable Long id) {
        return Result.success(emailService.getEmailLogDetail(id));
    }

    @PostMapping("/retry/{id}")
    public Result<String> retryFailedEmail(@PathVariable Long id) {
        boolean success = emailService.retryFailedEmail(id);
        return success ? Result.success("重试成功") : Result.fail(ResultCode.FAIL,"重试失败");
    }

    @GetMapping("/statistics")
    public Result<EmailStatistics> getEmailStatistics(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {

        EmailStatsQuery query = new EmailStatsQuery();
        query.setStartTime(startTime);
        query.setEndTime(endTime);

        return Result.success(emailService.getEmailStatistics(query));
    }


    // 辅助方法
    private EmailMessage convertToEmailMessage(EmailRequest request) throws IOException {
        EmailMessage.EmailMessageBuilder builder = EmailMessage.builder()
                .email(request.getEmail())
                .subject(request.getSubject())
                .content(request.getContent())
                .isHtml(request.getIsHtml());

        if (request.getAttachments() != null) {
            builder.attachments(request.getAttachments().stream()
                    .map(att -> {
                        try {
                            return EmailMessage.Attachment.builder()
                                    .filename(att.getFilename())
                                    .data(att.getFile().getBytes())
                                    .build();
                        } catch (IOException e) {
                            throw new RuntimeException("处理附件失败", e);
                        }
                    })
                    .collect(Collectors.toList()));
        }

        return builder.build();
    }

    private EmailMessage convertToEmailMessage(EmailRequest request, List<MultipartFile> attachments) throws IOException {
        EmailMessage.EmailMessageBuilder builder = EmailMessage.builder()
                .email(request.getEmail())
                .subject(request.getSubject())
                .content(request.getContent())
                .isHtml(request.getIsHtml());

        if (attachments != null && !attachments.isEmpty()) {
            builder.attachments(attachments.stream()
                    .map(file -> {
                        try {
                            return EmailMessage.Attachment.builder()
                                    .filename(file.getOriginalFilename())
                                    .data(file.getBytes())
                                    .build();
                        } catch (IOException e) {
                            throw new RuntimeException("处理附件失败", e);
                        }
                    })
                    .collect(Collectors.toList()));
        }

        return builder.build();
    }

}
